package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */

@RestController
@RequestMapping("/admin/common")
@Api(tags = "调用接口来了")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

//    @PostMapping("/upload")
//    @ApiOperation("文件上传go")
//    public Result<String> upload(MultipartFile file) {
//        log.info("我来上传文件，这个文件是：{}",file);
//        try {
//            String originalFilename = file.getOriginalFilename();
//            //截取原始文件的后缀 sdsd.png
//            String[] split = originalFilename.split("\\.");
//            String before_filename = split[0]; //得到文件的前缀
//
//            //得到文件的后缀
//            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//            //拼接文件名
//            String filenameStore = before_filename+"_"+UUID.randomUUID().toString() + extension;
//            //文件的请求路径
//            String filepath = aliOssUtil.upload(file.getBytes(), filenameStore);
//            return Result.success(filepath);
//        } catch (IOException e) {
//            log.error(MessageConstant.UPLOAD_FAILED);
//        }
//        return Result.error(MessageConstant.UPLOAD_FAILED);
//    }

    @PostMapping("/upload")
    @ApiOperation("文件上传go")
    public Result<String> upload(MultipartFile file) {
        log.info("我来上传文件，这个文件是：{}",file);
        //获取文件后缀
        String originalFilename = file.getOriginalFilename();
        //设置请求前缀
        String requestHeader = "http://localhost:8080/image/";

        String objectName = UUID.randomUUID().toString()+originalFilename;

        try{
            file.transferTo(new File("E:\\_JAVA_PATH\\hm-cqwaimai\\sky-server\\image\\" + objectName));
            log.info("上传成功!");
            return Result.success(requestHeader + objectName);
        } catch (Exception e) {
            log.error("文件上传失败"+e);
            e.printStackTrace();
        }
        return null;
    }

}
